#!/usr/bin/env bash
MIN_VERSION="17"
echoerr() { echo "$@" 1>&2; }

if type -p java >/dev/null; then
    _java=java
elif [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]];  then
    _java="$JAVA_HOME/bin/java"
else
    echoerr -e "\033[1;31mError:\033[0m K requires Java $MIN_VERSION to run but Java was not detected."
    echoerr "Please either add it to PATH or set the JAVA_HOME environment variable."
    exit 1
fi

function setarch {
  echo $version | grep '64-Bit' >& /dev/null
  if [ $? -eq 0 ]; then
    ARCH=64
  else
    ARCH=32
  fi
}

NG="$(dirname "${BASH_SOURCE[0]}")/bin/ng"
KSERVER_SOCKET="${KSERVER_SOCKET:-$HOME/.kserver}"
KSERVER_INSTANCE="$NG --nailgun-server local:$KSERVER_SOCKET/socket"
version=$($KSERVER_INSTANCE org.kframework.main.JavaVersion 2>&1)
if [ $? -eq 0 ]; then
  setarch
  JAVA="$KSERVER_INSTANCE"
else
  version=$($NG org.kframework.main.JavaVersion 2>&1)
  if [ $? -eq 0 ]; then
    setarch
    JAVA=$NG
  else
    version=$("$_java" --version)
    setarch
    if [ $ARCH -eq 64 ]; then
      TIERED=-XX:+TieredCompilation
    fi
    export K_OPTS="-Xms64m -Xmx8192m -Xss32m $TIERED $K_OPTS"
    JAVA="java -Dfile.encoding=UTF-8 -Djava.awt.headless=true $K_OPTS -ea -cp \"$(dirname "$BASH_SOURCE")/java/*:$HOME/.local/lib/kframework/java/*\""
  fi
fi

# The Java version information we're parsing here looks something like this:
#
#   openjdk 21.0.2 2024-01-16
#   OpenJDK Runtime Environment Homebrew (build 21.0.2)
#   OpenJDK 64-Bit Server VM Homebrew (build 21.0.2, mixed mode, sharing)
#
# To get the major version, we need to look at the first line's second field,
# then use a regex to extract the major version component. If the JVM changes
# the format of the version that gets printed, this script needs to be updated
# as well.

version=$(echo "$version" | head -1 | cut -d ' ' -f2)
version=$(echo "$version" | sed -e 's/\([0-9]*\)\(.*\)/\1/; 1q')

if [[ "$version" -lt "$MIN_VERSION" ]]; then
    echoerr -e "\033[1;31mError:\033[0m K requires Java $MIN_VERSION to run but the detected version is $version."
    echoerr "Please either add Java $MIN_VERSION bin directory to the PATH or set the JAVA_HOME
environment variable accordingly."
    exit 2
fi
